#include "us_ticker_api.h"
#include <stddef.h>
#include <Arduino.h>

static ticker_event_queue_t events = { 0 };

static ticker_irq_handler_type irq_handler = ticker_irq_handler;


bool _us_ticker_initialized;

const ticker_info_t *us_ticker_get_info()
{
    static const ticker_info_t info = {
        1000,
        8
    };
    return &info;
}

static void note_us_ticker_init()
{
    //us_ticker_init();
    _us_ticker_initialized = true;
}

static void note_us_ticker_free()
{
    _us_ticker_initialized = false;
    //us_ticker_free();
}

uint32_t us_ticker_read()
{
    return millis();
}
void us_ticker_set_interrupt(timestamp_t timestamp)
{
    //sbi(TIMSK0, TOIE0);
}

void us_ticker_disable_interrupt(void)
{
    //cbi(TIMSK0, TOIE0);
}

void us_ticker_clear_interrupt(void)
{
    //api for arm
}

void us_ticker_fire_interrupt(void)
{
    //sbi(TIMSK0, TOIE0);
}
static const ticker_interface_t us_interface = {

    .init = note_us_ticker_init,//impl
    .read = us_ticker_read,//impl
    .disable_interrupt = us_ticker_disable_interrupt,//impl
    .clear_interrupt = us_ticker_clear_interrupt,//impl
    .set_interrupt = us_ticker_set_interrupt,//impl
    .fire_interrupt = us_ticker_fire_interrupt,//impl
    .get_info = us_ticker_get_info,//impl
    .free = note_us_ticker_free,//impl
    .runs_in_deep_sleep = false,
};

static const ticker_data_t us_data = {
    .interface = &us_interface,
    .queue = &events
};

const ticker_data_t *get_us_ticker_data(void)
{
    return &us_data;
}

ticker_irq_handler_type set_us_ticker_irq_handler(ticker_irq_handler_type ticker_irq_handler)
{
    ticker_irq_handler_type prev_irq_handler = irq_handler;

    irq_handler = ticker_irq_handler;

    return prev_irq_handler;
}

void us_ticker_irq_handler(void)
{
    if (irq_handler) {
        irq_handler(&us_data);
    }
}

void timer0_irq_handler()
{
    if (irq_handler) {
        irq_handler(&us_data);
    }
}